#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int eatenApples(vector<int>& apples, vector<int>& days) {
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> heap;
        int n = days.size(), res = 0;
        for (int i = 0; i < n || heap.size(); i++)
        {
            if (i < n)
                heap.push({ i + days[i], apples[i] });
            while (heap.size() && (heap.top().first <= i || heap.top().second <= 0)) heap.pop();
            if (heap.size())
            {
                pair<int, int> tmp = heap.top(); heap.pop();
                --tmp.second;
                ++res;
                heap.push(tmp);
            }
        }
        return res;
    }
};